<script setup lang="ts">
import type { InputInstance } from '@arco-design/web-vue'
import type { PropType } from 'vue'
import { computed, nextTick, ref } from 'vue'

defineOptions({ name: 'StringTags' })

const $props = defineProps({
  value: {
    type: String as PropType<string>,
    default: undefined,
  },
  btnText: {
    type: String as PropType<string>,
    default: undefined,
  },
})
const $emits = defineEmits(['update:value', 'change'])

const computedTags = computed({
  get: () => ($props.value && $props.value.length ? $props.value.split(',') : []),
  set: () => updateModalValue(),
})

const inputRef = ref<InputInstance | null>(null)
const editInput = ref<InputInstance[] | null>(null)
const showInput = ref(false)
const inputVal = ref('')
const activeIdx = ref(-1)

function handleOpenEdit(idx) {
  activeIdx.value = idx
  nextTick(() => {
    console.log(editInput.value)
    editInput.value?.[0]?.focus()
  })
}

function handleEdit() {
  showInput.value = true

  nextTick(() => {
    if (inputRef.value) {
      inputRef.value.focus()
    }
  })
}

function handleAdd() {
  if (inputVal.value) {
    computedTags.value.push(inputVal.value)
    inputVal.value = ''
  }
  showInput.value = false
  updateModalValue()
}

function handleUpdate(val) {
  if (typeof val !== 'string') {
    return (activeIdx.value = -1)
  }
  computedTags.value.splice(activeIdx.value, 1, val)
  activeIdx.value = -1
  updateModalValue()
}

function handleRemove(_: string, idx: number) {
  computedTags.value.splice(idx, 1)
  updateModalValue()
}

function updateModalValue() {
  const modalValue = computedTags.value.join(',')
  $emits('update:value', modalValue)
  $emits('change', modalValue)
}
</script>

<template>
  <a-space wrap class="a-string-tags">
    <template v-for="(tag, idx) of computedTags" :key="idx">
      <a-tag
        v-if="activeIdx !== idx"
        color="arcoblue"
        closable
        @click="handleOpenEdit(idx)"
        @close="handleRemove(tag, idx)"
      >
        <a-popover :content="tag">
          <span class="a-string-tag_content">{{ tag }}</span>
        </a-popover>
      </a-tag>

      <a-input
        v-if="activeIdx === idx"
        ref="editInput"
        :default-value="tag"
        @change="handleUpdate"
        @blur="handleUpdate"
      />
    </template>

    <a-input
      v-if="showInput"
      ref="inputRef"
      v-model.trim="inputVal"
      @keyup.enter="handleAdd"
      @blur="handleAdd"
    />
    <a-tag v-else color="arcoblue" :style="{ cursor: 'pointer' }" @click="handleEdit">
      <template #icon>
        <icon-plus />
      </template>
      {{ btnText || 'addTag' }}
    </a-tag>
  </a-space>
</template>

<style lang="scss">
  .arco-space.a-string-tags .arco-tag {
    max-width: 120px;
    .a-string-tag_content {
      word-break: break-all;
      white-space: nowrap;
      text-overflow: ellipsis;
      overflow: hidden;
    }
  }
</style>
